viewer = new Cesium.Viewer('cesiumContainer',{
    skyBox : false,
    skyAtmosphere : false,
    baseLayerPicker : false,
    //shouldAnimate : true
});
document.getElementsByClassName("cesium-infoBox-iframe")[0].sandbox="allow-same-origin allow-popups allow-forms allow-scripts";
var canvas = viewer.canvas;
canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
canvas.onclick = function() {
    canvas.focus();
};
var scene = viewer.scene;
var ellipsoid = viewer.scene.globe.ellipsoid; 
scene.imageryLayers.removeAll(true);
scene.globe.baseColor = new Cesium.Color(0.0, 0.0, 0.0,0.0); // 没有影像时地球的基础颜色，默认为蓝色
scene.globe.enableLighting=false;
scene.globe.depthTestAgainstTerrain=false;
scene.globe.showGroundAtmosphere=false;
$(".cesium-viewer-toolbar,.cesium-viewer-animationContainer,.cesium-viewer-timelineContainer,.cesium-viewer-bottom").css("display","none");
$(".cesium-viewer-fullscreenContainer .cesium-button").css("background","#000");
var selectedEntity = new Cesium.Entity(); 

/*for(var j = 0; j < 40; j++ ){
    addModel(viewer,116.39131703682953+j*0.00255 ,39.907379990947426,50,"第"+(2*j)+"-"+(2*j+2)+"米");
}*/
function addModel(viewer,lon,lat,ele,name){
    viewer.entities.add({
        name:name,
        position: Cesium.Cartesian3.fromDegrees(lon,lat,ele),
        model : {
            uri : '../../../static/cesium/data/jjxd.glb',
            scale : 1,
        }
    });
}


var addHandHole = function(bottom,left,start,wall,id,name){
    let height = 2.90;
    let width = 0.5;
    let tan = height/width;
    if(wall != "top"){
        if(wall == "left"){
            let left = bottom / tan;
            addButton(viewer,116.38995464596081 + 0.001272259573188883*start,39.909204434602684 - left * 0.00086 ,58.62427878900178 + 93.89683143187872 * bottom,0,0,0,id,name);
        }else if(wall == "right"){
            let right = bottom / tan;
            addButton(viewer,116.38995464596081 + 0.001272259573188883*start,39.90578505453292 + right * 0.00086 ,58.62427878900178 + 93.89683143187872 * bottom,0,0,0,id,name);
        }
    }else{
        addButton(viewer,116.38995464596081 + 0.001272259573188883*start,39.908825389827214 - left * 0.00086 ,298.3686263741616,0,0,0,id,name);
    }
}

//添加点的方法 单位是米  （距离底部，距离左侧，距离起始点，所在墙面，名称）
/*addHandHole(2,null,10,"left","探孔102");
addHandHole(1,null,10,"right","探孔102");
addHandHole(null,2,10,"top","探孔102");*/

function addButton(viewer,lon,lat,ele,head,pitch,roll,id,name){   	
    var hpRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(head), Cesium.Math.toRadians(pitch), Cesium.Math.toRadians(roll));
    var orientation = Cesium.Transforms.headingPitchRollQuaternion(Cesium.Cartesian3.fromDegrees(lon, lat, ele), hpRoll);
    var cam = viewer.entities.add({
    	id:id,
        name: name,
        type:'tk',
        position: Cesium.Cartesian3.fromDegrees(lon, lat, ele),
        //orientation: orientation,
        ellipsoid : {
            radii : new Cesium.Cartesian3(5.0, 5.0, 5.0),
            material : Cesium.Color.AQUA.withAlpha(1)
        }
    });
}
var eyePoint = Cesium.Cartesian3.fromDegrees( 116.39131703682953,39.907379990947426,160);
viewer.camera.setView({
    destination : eyePoint, // 设置位置
    orientation: {
        heading : Cesium.Math.toRadians(90), // 方向
        pitch : Cesium.Math.toRadians(0),// 倾斜角度
        roll : 0
    },
}); 

// disable the default event handlers
scene.screenSpaceCameraController.enableRotate = false;
scene.screenSpaceCameraController.enableTranslate = false;
scene.screenSpaceCameraController.enableZoom = false;
scene.screenSpaceCameraController.enableTilt = false;
scene.screenSpaceCameraController.enableLook = false;

var startMousePosition;
var mousePosition;
var flags = {
    looking : false,
    moveForward : false,
    moveBackward : false,
    moveUp : false,
    moveDown : false,
    moveLeft : false,
    moveRight : false
};

var handler = new Cesium.ScreenSpaceEventHandler(canvas);
handler.setInputAction(function(movement) {
    flags.looking = true;
    mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);

handler.setInputAction(function(movement) {
    mousePosition = movement.endPosition;
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

handler.setInputAction(function(position) {
    flags.looking = false;
}, Cesium.ScreenSpaceEventType.LEFT_UP);

function getFlagForKeyCode(keyCode) {
    switch (keyCode) {
    case 'W'.charCodeAt(0):
        return 'moveForward';
    case 'S'.charCodeAt(0):
        return 'moveBackward';
    case 'Q'.charCodeAt(0):
        return 'moveUp';
    case 'E'.charCodeAt(0):
        return 'moveDown';
    case 'D'.charCodeAt(0):
        return 'moveRight';
    case 'A'.charCodeAt(0):
        return 'moveLeft';
    default:
        return undefined;
    }
}

document.addEventListener('keydown', function(e) {
    var flagName = getFlagForKeyCode(e.keyCode);
    if (typeof flagName !== 'undefined') {
        flags[flagName] = true;
    }
}, false);

document.addEventListener('keyup', function(e) {
    var flagName = getFlagForKeyCode(e.keyCode);
    if (typeof flagName !== 'undefined') {
        flags[flagName] = false;
    }
}, false);

viewer.clock.onTick.addEventListener(function(clock) {
    var camera = viewer.camera;
    var lonlat = cartesianToWGS84(viewer.camera.position.x,viewer.camera.position.y,viewer.camera.position.z);
    //console.log(lonlat);

    //116.39131703682953+j*0.00255
    let dis = (lonlat.lon-116.38995464596081)/0.001272259573188883;
    document.getElementById("dis").innerText = dis.toFixed(2) +"m";

    if(lonlat.lat >= 39.90842977074004){
        //flags["moveLeft"] = false;   
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(lonlat.lon,39.90842977074004,lonlat.ele);
    }
    if(lonlat.lat <= 39.90624795809176){
        //flags["moveRight"] = false;  
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(lonlat.lon,39.90624795809176,lonlat.ele);  
    }

    if(lonlat.lon >= 116.47768697675383){
        //flags["moveForward"] = false;    
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(116.47768697675383,lonlat.lat,lonlat.ele);  
    }

    if(lonlat.lon <= 116.39046396172458){
        //flags["moveBackForward"] = false;  
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(116.39046396172458,lonlat.lat,lonlat.ele);  
    }

    if(lonlat.ele <= 74.25515327948877){
        //flags["moveDown"] = false;   
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(lonlat.lon,lonlat.lat,74.25515327948877);   
    }

    if(lonlat.ele >= 281.88908419900923){
        //flags["moveUp"] = false;    
        viewer.camera.position =  Cesium.Cartesian3.fromDegrees(lonlat.lon,lonlat.lat,281.88908419900923);  
    }


    if (flags.looking) {
        var width = canvas.clientWidth;
        var height = canvas.clientHeight;

        // Coordinate (0.0, 0.0) will be where the mouse was clicked.
        var x = (mousePosition.x - startMousePosition.x) / width;
        //var y = -(mousePosition.y - startMousePosition.y) / height;

        var lookFactor = 0.15;
        camera.lookRight(x * lookFactor);
        //camera.lookUp(y * lookFactor);
    }
 
    var cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
    var moveRate = cameraHeight / 10.0;

    if (flags.moveForward) {
        camera.moveForward(moveRate);
    }
    if (flags.moveBackward) {
        camera.moveBackward(moveRate);
    }
    if (flags.moveUp) {
        camera.moveUp(moveRate);
    }
    if (flags.moveDown) {
        camera.moveDown(moveRate);
    }
    if (flags.moveLeft) {
        camera.moveLeft(moveRate);
    }
    if (flags.moveRight) {
        camera.moveRight(moveRate);
    }
});


var disTemp = 2;
viewer.camera.changed.addEventListener(function(percentage) {

}); 

function cartesianToWGS84(x,y,z){
    let ellipsoid=viewer.scene.globe.ellipsoid;
    let cartesian3=new Cesium.Cartesian3(x,y,z);
    let cartographic = ellipsoid.cartesianToCartographic(cartesian3);
    let lat = Cesium.Math.toDegrees(cartographic.latitude);
    let lon = Cesium.Math.toDegrees(cartographic.longitude);
    let ele = cartographic.height;
    return {lon,lat,ele}
}

function setReferenceFrame5(viewer,x,y,z,h,p,r,fs) {            	
    var setView;
    fs=="f"? setView="flyTo":setView="setView"
    viewer.camera[setView]({
        
        destination :{x: x, y:y, z: z}, //Cesium.Cartesian3.fromDegrees(116.44143400834318,39.524458636290575,180.0),
        orientation: {
            heading : Cesium.Math.toRadians(h), // 方向
            pitch : Cesium.Math.toRadians(p),// 倾斜角度
            roll : Cesium.Math.toRadians(r)
        },
        //duration:3,
    }); 
}

var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);//屏蔽双击事件

var selectedEntity = new Cesium.Entity(); 
viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
    var pickedFeature = viewer.scene.pick(movement.position);
    
    if (Cesium.defined(pickedFeature)) {
       // if ( pickedFeature.id._name.slice(0,2) == "探孔" ) { 
         if ( pickedFeature.id.type == "tk" ) {
 			$.ajax({
				url: "../../mine/point/findByHoleId",
				data: {"holeId":pickedFeature.id.id},
				success: function(data){
					var result= [];
					if(data.length != 0){
						for(var i=0;i<data.length;i++){
							var obj = new Object();
							obj.name= data[i].composition;
							obj.type = "shui";
							var key = data[i].composition;
							if(i==0){
								obj.data= [0,data[i].position];
							}else{
								obj.data = [data[i-1].position,data[i].position];
							}	
							result.push(obj);
						}
					}
					  selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';
			           
			            var listHtml = "";
			            for(let i in result){
			                listHtml += '<tr><th>' + result[i].name + '</th><td>' +result[i].data[1] + '</td></tr>'
			            }

			            viewer.selectedEntity = selectedEntity;
			            selectedEntity.name = pickedFeature.id._name;
			            selectedEntity.description = 
			            '<table class="cesium-infoBox-defaultTable"  ><tbody>' +listHtml+

			            
			            '</tbody></table>'+
			            '<iframe style="height:300px;width:100%;margin:0px;border:0px;padding:0px"  src="3dRation?holeId='+pickedFeature.id.id+'" ></iframe>';   
					
				}
			}) 
          
        }        
    }
    else {
        return;
    }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

handler.setInputAction(function(wheelment){
     
},Cesium.ScreenSpaceEventType.WHEEL);

